import axios from 'axios'
import { store } from '@/store'
import { request } from '@/enums/base'

// let requestCount = 0 // 当前请求数量
const DEFAULT_TIMEOUT = 20 * 1000 // 接口请求超时时间
// 接口的返回状态码
enum RETURN_CODE {
  SUCCESS = 200,
  CREATE = 201,
  TOKEN_EXPIRED = 401, // token 过期
}
// 接口接通，但是还要判断一层后端返回的状态码
enum STATUS_CODE {
  SUCCESS = 200,
}

// interface Iconfig {
//   loading?: boolean
//   error?: boolean
//   timeout?: number
//   header?: object
// }

const axiosInstance = axios.create({
  timeout: DEFAULT_TIMEOUT,
  responseType: 'json',
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
})

// 请求拦截
axiosInstance.interceptors.request.use((config) => {
  store.request.add()
  const { url } = config
  return {
    ...config,
    baseURL: request.API_PREFIX,
    url,
  }
})

// 响应拦截
axiosInstance.interceptors.response.use((response) => {
  store.request.sub()
  if (!response || !response.data) {
    // message.error(response?.msg || '网络错误')
    return Promise.reject()
  }

  if (response.status !== RETURN_CODE.SUCCESS) {
    return Promise.reject('接口不成功')
  }

  switch (response.data.code) {
    case STATUS_CODE.SUCCESS:
      return response.data
    default:
      return Promise.reject(response.data)
  }
}, () => {
  store.request.sub()
})

const get = (url = '', params = {}) =>
  axiosInstance.get(url, { params })

const post = (url = '', data = {}) =>
  axiosInstance.post(url, data)

export { get, post }
